const { Op } = require("sequelize");
const Blog = require("./models/Blog");
const BlogType = require("./models/BlogType");

// 添加一篇文章
exports.createOneBlogDao = async (data) => {
    return await Blog.create(data);
}

// 获取一篇文章
exports.findOnBlogDao = async (id) => {
    return await Blog.findOne({
        where: {
            id
        },
        include: {
            model: BlogType,
            as: "category",
            attributes: ["id", "name"]
        },
    });
}

/**
 * 分页获取文章
 * @param {Number} offset 跳过多少条数据
 * @param {Number} limit 获取多少条数据
 */
exports.pagingFindBlogDao = async (offset, limit, where) => {
    return await Blog.findAndCountAll({
        offset,
        limit,
        where,
        include: {
            model: BlogType,
            as: "category",
            attributes: ["id", "name"]
        },
        attributes: {
            exclude: ["categoryId"]
        }
    })
}

/**
 * 修改文章
 * @param {Object} newBlog 新文章对象
 * @param {Number} id 文章id
 */
exports.updateOneBlogDao = async (newBlog, id) => {
    return await Blog.update(newBlog, {
        where: {
            id
        }
    })
}


/**
 * 删除一片文章
 * @param {Number} id 文章id
 * @returns 
 */
exports.deleteOneBlogDao = async (id) => {
    return await Blog.destroy({
        where: {
            id
        }
    })
}

exports.increaseBlogScanNumber = async (id) => {
    const blog = await Blog.findByPk(id);
    blog.scanNumber++;
    await blog.save();
}